<template>
  <!-- copy from stock-components-BatchIndividual -->
  <PageDialog
    title="请选择替换数据"
    v-model:visible="showDialog"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <basic-information :info="infoList" :label-width="infoList.labelWidth" />
    <new-page-filter
      v-model:query="filterInfo.query"
      :query-more-json="false"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
    >
    </new-page-filter>
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="table-top-msg">
          <div class="table-top-msg-left">可选择替代产品</div>
          <div class="table-top-msg-left">
            <el-button @click="removeRight">右移</el-button>
          </div>
        </div>
        <DialogTable
          ref="leftTableInfoRef"
          :refresh="leftTableInfo.refresh"
          :init-curpage="leftTableInfo.initCurpage"
          v-model:data="leftTableInfo.data"
          :api="leftTableInfo.api"
          :reserve-selection="true"
          :listen-height="false"
          :check-box="true"
          check-box-fixed="right"
          v-model:query="filterInfo.query"
          :field-list="leftTableInfo.fieldList"
          :handle="leftTableInfo.handle"
          @handleEvent="leftHandleEvent"
        >
        </DialogTable>
      </el-col>
      <el-col :span="12">
        <div class="table-top-msg">
          <div class="table-top-msg-right">
            <el-button @click="removeLeft">左移</el-button>
          </div>
          <div class="table-top-msg-right">已选择替代产品</div>
        </div>
        <el-form :model="rightTableInfo" ref="tableForm" style="width: 100%">
          <DialogTable
            ref="rightTableInfoRef"
            v-model:data="rightTableInfo.data"
            :reserve-selection="true"
            :listen-height="false"
            :pager="false"
            :check-box="true"
            checkBoxFixed="left"
            :field-list="rightTableInfo.fieldList"
            :handle="rightTableInfo.handle"
            @handleEvent="rightHandleEvent"
          >
            <template v-slot:col-editQty="scope">
              <el-form-item
                :prop="`data.${scope.$index}.editQty`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          validator: $validate.positive,
                          trigger: 'change',
                        },
                      ]
                    : []
                "
              >
                <el-input-number
                  v-model="scope.row.editQty"
                  :min="0"
                  :max="scope.row.calcQty"
                   controls-position="right"
                  :disabled="
                    scope.row.codeType === 2 || scope.row.codeType === 3
                  "
                >
                </el-input-number>
              </el-form-item>
            </template>
          </DialogTable>
        </el-form>
      </el-col>
    </el-row>
  </PageDialog>
</template>

<script setup name="batchIndividual">
import { getCustomizeSetting } from '@/api/customize'
import {
  getDepotFrozenStockChangePage,
  getDepotFrozenStockChangeSave,
  getDepotFrozenStockChangeById,
} from '@/api/dataQuery'
import { getSupplierAll } from '@/api/core'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
  },
  row: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {
    id: props.row.id,
    frozenType: props.row.frozenType,
    changeType: '',
    uniqueCode: '',
    factorySubCode: '',
    supplierIds: [],
    storeBatchNumber: '',
    frozenIdNotIn: '',
    depotStockIdNotIn: '',
  },
  searchList: [
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
      componentType: 'input',
      type: 'column',
      show: true,
      hidden: false,
    },
    {
      label: '个体码',
      value: 'uniqueCode',
      componentType: 'input',
      type: 'column',
      show: true,
      hidden: false,
    },
    {
      label: '原厂从码',
      value: 'factorySubCode',
      componentType: 'input',
      type: 'column',
      show: true,
      hidden: false,
    },
    {
      label: '供应商',
      value: 'supplierName',
      asValue: 'supplierIds',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: {
        supplierAuth: 'supplierId',
        sort: 'create_time desc',
      },
      clearable: true,
      filterable: true,
      multiple: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      show: true,
      hidden: false,
    },
    {
      label: '替换类型',
      value: 'changeType',
      componentType: 'select-model',
      code: 'frozen_change_type',
      multiple: true,
      clearable: false,
      show: true,
      hidden: false,
    },
  ],
  btnList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: getleftList },
    { type: 'button', label: '重置', event: clearSearch },
  ],
})
// 搜索
const tableKey = ref(
  'DepotFrozenStockVOList-com.slip.spd.entity.vo.stock.DepotFrozenStockVO'
)

const infoList = ref({
  data: {
    ...props.row,
  },
  fieldList: [
    { label: '通用名称', value: 'commonName', type: 'text' },
    { label: '产品编码', value: 'productCode', type: 'text' },
    { label: '规格', value: 'standard', type: 'text' },
    { label: '厂家', value: 'brandName', type: 'text' },
    { label: '条码类型', value: 'codeTypeValue', type: 'text' },
    { label: '冻结业务单号', value: 'orderNo', type: 'text' },
    { label: '冻结类型', value: 'frozenTypeValue', type: 'text' },
    { label: '冻结数量', value: 'qty', type: 'text' },
    { label: '批号', value: 'batchNumber', type: 'text' },
    { label: '批次号', value: 'storeBatchNumber', type: 'text' },
  ],
})

// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '替换类型',
      value: 'changeTypeValue',
    },
    {
      label: '批次号',
      value: 'storeBatchNumber',
    },
    {
      label: '个体码',
      value: 'uniqueCode',
    },
    {
      label: '原厂从码',
      value: 'factorySubCode',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '单价',
      value: 'price',
    },
    {
      label: '可替代数量',
      value: 'calcQty',
    },
  ],
})
const rightTableInfo = ref({
  data: [],
  fieldList: [
    {
      label: '替换类型',
      value: 'changeTypeValue',
    },
    {
      label: '批次号',
      value: 'storeBatchNumber',
    },
    {
      label: '替代数量',
      value: 'editQty',
      type: 'slot',
      width: 170,
    },
    {
      label: '可替代数量',
      value: 'calcQty',
    },
    {
      label: '个体码',
      value: 'uniqueCode',
    },
    {
      label: '原厂从码',
      value: 'factorySubCode',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '单价',
      value: 'price',
    },
  ],
  selections: [],
})

// 弹窗相关
const dialogInfo = ref({
  btLoading: false,
  width: '90%',
  btList: [
    { label: '取消', event: handleClose, show: true },
    { label: '确认', event: handleSave, show: true },
  ],
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQueryMap)
  getleftList()
}
// 关闭弹窗前的回调
function handleClose() {
  showDialog.value = false
  emits('reset')
}

function handleSave() {
  proxy.$refs.tableForm.validate((valid) => {
    if(valid){
      let editQtyNum = 0
      rightTableInfo.value.data.forEach((element) => {
        editQtyNum += element.editQty
      })
      if (editQtyNum > props.row.qty) {
        proxy.$message({
          showClose: true,
          message: `替代数量总数不能大于冻结数量！`,
          type: 'warning',
        })
        return
      }
      getDepotFrozenStockChangeSave({
        mainId: props.row.id,
        depotFrozenChangeDTOList: rightTableInfo.value.data,
      }).then((res) => {
        if ((res.code === 200) & res.success) {
          emits('callback', rightTableInfo.value.data)
          handleClose()
        }
      })
    }
  })
}

function initQuery() {
  filterInfo.value.copyQueryMap = proxy.$fn.deepClone(filterInfo.value.query)
}

function getleftList() {
  proxy.$nextTick(() => {
    leftTableInfo.value.api = getDepotFrozenStockChangePage
    leftTableInfo.value.refresh = Math.random()
  })
}

async function removeRight() {
  //左边往右移
  let selections = leftTableInfo.value.selections
  if (selections.length) {
    rightTableInfo.value.data = rightTableInfo.value.data.concat(selections)
    let fallFozenId = rightTableInfo.value.data.map((item) => {
      if (item.changeType === 1 && item.frozenId) {
        return item.frozenId
      }
    })
    fallFozenId = fallFozenId.filter((s) => {
      return s
    })
    let allDepotStockId = rightTableInfo.value.data.map((item) => {
      if (item.changeType !== 1 && item.depotStockId) {
        return item.depotStockId
      }
    })
    allDepotStockId = allDepotStockId.filter((s) => {
      return s
    })
    rightTableInfo.value.data.forEach((element) => {
      element['editQty'] = 1
    })
    filterInfo.value.query.frozenIdNotIn = fallFozenId.length
      ? fallFozenId.join(',')
      : ''
    filterInfo.value.query.depotStockIdNotIn = allDepotStockId.length
      ? allDepotStockId.join(',')
      : ''
  }
  getleftList()
  proxy.$refs['leftTableInfoRef'].clearSelection()
}
async function removeLeft() {
  //右边往左移
  let selections = rightTableInfo.value.selections
  if (selections.length) {
    rightTableInfo.value.data = rightTableInfo.value.data.filter(
      (item) => !selections.includes(item)
    )
    let fallFozenId = rightTableInfo.value.data.map((item) => {
      if (item.changeType === 1 && item.frozenId) {
        return item.frozenId
      }
    })
    fallFozenId = fallFozenId.filter((s) => {
      return s
    })
    let allDepotStockId = rightTableInfo.value.data.map((item) => {
      if (item.changeType !== 1 && item.depotStockId) {
        return item.depotStockId
      }
    })
    allDepotStockId = allDepotStockId.filter((s) => {
      return s
    })
    filterInfo.value.query.frozenIdNotIn = fallFozenId.length
      ? fallFozenId.join(',')
      : ''
    filterInfo.value.query.depotStockIdNotIn = allDepotStockId.length
      ? allDepotStockId.join(',')
      : ''
  }
  getleftList()
  proxy.$refs['rightTableInfoRef'].clearSelection()
}

function leftHandleEvent(event, data) {
  if (event === 'list') {
    leftTableInfo.value.data = data
  }
  if (event === 'tableCheck') {
    leftTableInfo.value.selections = data
  }
}
function rightHandleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      rightTableInfo.value.selections = data
      break
  }
}
function _getDepotFrozenStockChangeById() {
  getDepotFrozenStockChangeById(props.row.id).then((res) => {
    if (res && res.success) {
      props.row = res.data
      getleftList()
    }
  })
}
_getDepotFrozenStockChangeById()
initQuery()
</script>

<style lang="scss" scoped>
.table-top-msg {
  width: 100%;
  display: flex;
  align-items: center;
  .table-top-msg-left,
  .table-top-msg-right {
    width: 50%;
    display: flex;
    align-items: center;
  }
  .table-top-msg-left {
    justify-content: flex-end;
  }
  .table-top-msg-right {
    justify-content: flex-start;
  }
}
</style>
<style lang="scss">
.number-input .el-input-number__decrease,
.number-input .el-input-number__increase {
  height: 95% !important;
}
</style>
